package com.hsy.linemoney.modules.common;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.deparse.dpframe.tools.utils.DPLogUtil;

/**
 * Created by MartinKent on 2016/7/12.
 */
public class RadioGroup extends LinearLayout implements CompoundButton.OnCheckedChangeListener {
    private boolean isInited = false;
    private int checkedIndex = -1;

    public RadioGroup(Context context) {
        super(context);
    }

    public RadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RadioGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (!isInited) {
            init();
        }
    }

    private void init() {
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.setTag(i);
            if (child instanceof RadioButton) {
                ((RadioButton) child).setOnCheckedChangeListener(this);
                if (((RadioButton) child).isChecked()) {
                    checkedIndex = i;
                }
            }
        }
        isInited = true;
    }

    private boolean isChanging = false;

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!isChanging) {
            isChanging = true;
            checkedIndex = (int) buttonView.getTag();
            for (int i = 0; i < getChildCount(); i++) {
                View child = getChildAt(i);
                child.setTag(i);
                if (child instanceof RadioButton) {
                    DPLogUtil.d("setChecked(false)");
                    ((RadioButton) child).setChecked(false);
                }
            }
            buttonView.setChecked(true);
            isChanging = false;
        }
    }

    public int getCheckedIndex() {
        return checkedIndex;
    }
}
